<template>
  <NavBar title="金额记录" color="#fff" colorText="#333" brg="#f8f8f8">
  <view class="amount-record-container">
    
    <!-- 标签页 -->
    <view class="tab-container">
      <view 
        class="tab-item left" 
        :class="{ active: activeTab === 'all' }"
        @click="switchTab('all')"
      >
        <text class="tab-text">全部</text>
        <view class="tab-indicator" v-if="activeTab === 'all'"></view>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'income' }"
        @click="switchTab('income')"
      >
        <text class="tab-text">收入</text>
        <view class="tab-indicator" v-if="activeTab === 'income'"></view>
      </view>
      <view 
        class="tab-item right" 
        :class="{ active: activeTab === 'expense' }"
        @click="switchTab('expense')"
      >
        <text class="tab-text">使用</text>
        <view class="tab-indicator" v-if="activeTab === 'expense'"></view>
      </view>
    </view>
    
    <!-- 记录列表 -->
    <scroll-view
      class="record-list-container"
      scroll-y="true"
      @scrolltolower="onScrollToLower"
      lower-threshold="100"
    >
      <view class="record-list">
        <view
          class="record-item"
          v-for="(record, index) in filteredRecords"
          :key="record.id"
        >
          <view class="record-header">
           <view>
  			 <text class="order-number">{{ record.orderNumber }}</text>
  			 <image class="copy-icon" src="/static/record.png" mode="" @click="copyOrderNumber(record.orderNumber)"></image>
  		 </view>
  		  <view class="record-content">
  		    <text class="status-text">{{ record.status }}</text>
  		  </view>
          </view>
          <view >
            <text class="record-desc">{{ record.description }}</text>

          </view>
          <view class="record-amount" :class="{ income: record.type === 'income' }">
            <text class="amount-text">{{ record.amount > 0 ? '+' : '' }}{{ record.amount }}元</text>
          </view>
          <view class="record-time">
  			<text>时间</text>
  			<text>{{ record.time }}</text>
  		</view>
          <view class="record-divider" v-if="index < filteredRecords.length - 1"></view>
        </view>

        <!-- 加载状态 -->
        <view class="load-more" v-if="loading || hasMore">
          <view v-if="loading" class="loading-text">
            <text>加载中...</text>
          </view>
          <view v-else-if="hasMore" class="load-more-text">
            <text>上拉加载更多</text>
          </view>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-if="filteredRecords.length === 0 && !loading">
          <image class="empty-icon" src="/static/empty.png" mode="widthFix"></image>
          <text class="empty-text">暂无记录</text>
        </view>
      </view>
    </scroll-view>
  </view>
  </NavBar>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { WALLET_API } from '../../config/api.js'
import { getCurrentUser, getToken } from '../../utils/user.js'

// 响应式数据
const activeTab = ref('all')

// 钱包日志数据
const walletLogs = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const loading = ref(false)
const hasMore = ref(true)
const total = ref(0)



// 获取钱包日志数据
const fetchWalletLogs = async (reset = false) => {
  if (loading.value) return

  try {
    loading.value = true

    if (reset) {
      currentPage.value = 1
      walletLogs.value = []
      hasMore.value = true
    }

    const token = getToken()
    if (!token) {
      console.error('未找到用户token')
      return
    }

    // 构建请求参数
    const params = {
      asset_code: 'AGENT_CASH',
      page: currentPage.value,
      page_size: pageSize.value
    }

    // 根据标签页添加操作类型筛选
    if (activeTab.value === 'income') {
      params.op_type = 1 // 收入
    } else if (activeTab.value === 'expense') {
      params.op_type = 2 // 使用
    }
    // 全部不传op_type参数

    // 构建查询字符串
    const queryString = Object.keys(params)
      .filter(key => params[key] !== undefined)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')

    const response = await uni.request({
      url: `${WALLET_API.LOGS}?${queryString}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })

    console.log('钱包日志API响应:', response)

    if (response.statusCode === 200 && response.data.code === 200) {
      const responseData = response.data.data || {}
      const newData = responseData.logs || []

      // 更新总数据量和分页信息
      total.value = responseData.total || 0
      hasMore.value = responseData.has_more || false

      if (reset) {
        walletLogs.value = newData
        currentPage.value = 1
      } else {
        walletLogs.value = [...walletLogs.value, ...newData]
      }

      console.log('钱包日志加载成功:', {
        currentPage: currentPage.value,
        currentDataCount: walletLogs.value.length,
        total: total.value,
        hasMore: hasMore.value,
        newDataLength: newData.length
      })
    } else {
      const errorMessage = response.data?.data?.error_message || response.data?.error_message || response.data?.message || '获取钱包日志失败'
      uni.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
    }

  } catch (error) {
    console.error('获取钱包日志失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none',
      duration: 3000
    })
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return ''

  try {
    // 解析ISO时间格式：2025-09-23T16:36:55.062+08:00
    const date = new Date(timeString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch (error) {
    console.error('时间格式化失败:', error)
    return timeString
  }
}

// 处理memo字段，用中文逗号分隔
const parseMemo = (memo, index = 0) => {
  if (!memo) return ''

  const parts = memo.split('，')
  return parts[index] || ''
}

// 处理API数据为显示格式
const processWalletLogData = (apiData) => {
  if (!apiData || !Array.isArray(apiData)) {
    return []
  }

  return apiData
    .filter(item => item.biz_type !== 'GENESIS') // 过滤掉GENESIS类型
    .map(item => {
      let orderNumber = ''
      let description = ''
      let status = ''

      // 根据biz_type处理不同的显示格式
      if (item.biz_type === 'AGENT_RECHARGE') {
        // AGENT_RECHARGE类型处理
        description = item.memo || '代理商充值'
        status = '已完成'
        orderNumber = `订单号 ${item.ref_pay_no || ''}`
      } else if (item.biz_type === 'CARD_REDEEM') {
        // CARD_REDEEM类型处理
        description = parseMemo(item.memo, 0) // 第一段
        status = '已生成'
        orderNumber = parseMemo(item.memo, 1) // 第二段
      } else {
        // 其他类型的默认处理
        description = item.memo || '未知操作'
        status = '已完成'
        orderNumber = `记录号 ${item.id}`
      }

      return {
        id: item.id,
        orderNumber: orderNumber,
        description: description,
        status: status,
        amount: parseFloat(item.delta_balance) || 0,
        type: item.op_type === 1 ? 'income' : 'expense',
        time: formatTime(item.created_at),
        rawData: item
      }
    })
}

// 计算属性 - 根据当前标签过滤记录
const filteredRecords = computed(() => {
  // 使用API数据而不是模拟数据
  const processedData = processWalletLogData(walletLogs.value)

  if (activeTab.value === 'all') {
    return processedData
  } else if (activeTab.value === 'income') {
    return processedData.filter(record => record.type === 'income')
  } else if (activeTab.value === 'expense') {
    return processedData.filter(record => record.type === 'expense')
  }
  return processedData
})

// 方法
const goBack = () => {
  uni.navigateBack()
}

const switchTab = (tab) => {
  activeTab.value = tab
  // 切换标签页时重新加载数据
  fetchWalletLogs(true)
}

// 滚动到底部加载更多
const onScrollToLower = () => {
  console.log('滚动到底部，检查是否需要加载更多数据')

  // 如果正在加载或没有更多数据，则不执行
  if (loading.value || !hasMore.value) {
    console.log('跳过加载：', { loading: loading.value, hasMore: hasMore.value })
    return
  }

  console.log('开始加载下一页数据，当前页：', currentPage.value)

  // 增加页码并加载下一页
  currentPage.value++
  fetchWalletLogs(false)
}

// 复制订单号到粘贴板
const copyOrderNumber = (orderNumber) => {
  if (!orderNumber) {
    uni.showToast({
      title: '订单号为空',
      icon: 'none',
      duration: 2000
    })
    return
  }

  uni.setClipboardData({
    data: orderNumber,
    success: () => {
      uni.showToast({
        title: '复制成功',
        icon: 'success',
        duration: 2000
      })
    },
    fail: () => {
      uni.showToast({
        title: '复制失败',
        icon: 'none',
        duration: 2000
      })
    }
  })
}

// 页面加载时初始化数据
onMounted(() => {
  fetchWalletLogs(true)
})
</script>

<style scoped>
.amount-record-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #C2DDFF 0%, #FFFFFF 100%);
  border-radius: 0rpx 0rpx 0rpx 0rpx;
  padding-top: 160rpx;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 88rpx;
  padding: 20rpx 40rpx 10rpx;
  background: transparent;
  box-sizing: border-box;
}

.time {
  font-size: 32rpx;
  font-weight: 600;
  color: #000000;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.signal-icon,
.wifi-icon,
.battery-icon {
  width: 24rpx;
  height: 16rpx;
  background: #000000;
  border-radius: 2rpx;
}

.battery-icon {
  width: 32rpx;
  height: 16rpx;
  position: relative;
}

.battery-icon::after {
  content: '';
  position: absolute;
  right: -6rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 4rpx;
  height: 8rpx;
  background: #000000;
  border-radius: 0 2rpx 2rpx 0;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 40rpx;
  height: 88rpx;
}

.nav-left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 48rpx;
  font-weight: 300;
  color: #000000;
  line-height: 1;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #000000;
  flex: 1;
  text-align: center;
  margin-left: -60rpx;
}

.nav-right {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-box {
  width: 120rpx;
  height: 60rpx;
  background: #F5F5F5;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-placeholder {
  font-size: 24rpx;
  color: #999999;
}

/* 标签页 */
.tab-container {
  display: flex;
  padding: 0 40rpx;
  margin-bottom: 10rpx;
  padding-top: 20rpx;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;
  position: relative;
}

.tab-text {
  font-size: 32rpx;
  font-weight: 500;
  color: #999999;
  transition: color 0.3s ease;
}

.tab-item.active .tab-text {
  color: #000000;
}

.tab-indicator {
  width: 40rpx;
  height: 6rpx;
  background: #8B5CF6;
  border-radius: 3rpx;
  margin-top: 8rpx;
}

/* 记录列表容器 */
.record-list-container {
  height: calc(100vh - 200rpx);
  margin: 0 30rpx;
  background: #FFFFFF;
  border-radius: 20rpx 20rpx 20rpx 20rpx;
  width: 92%;
}

/* 记录列表 */
.record-list {
  padding: 0 40rpx;
  min-height: 80%;
}

.record-item {
  position: relative;
  padding: 30rpx 0;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.order-number {
  font-size: 24rpx;
  color: #666666;
  flex: 1;
}

.copy-icon {
  width:25rpx;
  height: 25rpx;
  margin-left: 30rpx;
  cursor: pointer;
  transition: opacity 0.3s ease;
}
.left{
	align-items:flex-start!important;
}
.right{
		align-items:flex-end!important;
}
.copy-icon:active {
  opacity: 0.7;
}

.record-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  height: 38rpx;
  border: 1px dashed #999;
  padding:0 10rpx;
  margin-top: 10rpx;
  color: #999999;
  background-color: #f5f5f5;
  
}

.record-desc {
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
  flex: 1;
}

.record-status {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  background: #F5F5F5;
}

.status-text {
  font-size: 22rpx;
  color: #666666;
  font-weight: 500;
}

.status-completed {
  background: #F0F9FF;
}

.status-completed .status-text {
  color: #1890FF;
}

.status-generated {
  background: #F6FFED;
}

.status-generated .status-text {
  color: #52C41A;
}

.status-voided {
  background: #FFF2E8;
}

.status-voided .status-text {
  color: #FA8C16;
}

.status-pending {
  background: #FFF7E6;
}

.status-pending .status-text {
  color: #FA8C16;
}

.status-closed {
  background: #F5F5F5;
}

.status-closed .status-text {
  color: #999999;
}

.record-amount {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  margin-top: 20rpx;
}

.amount-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}



.record-time {
  font-size: 24rpx;
  color: #999999;
  margin-top: 8rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #999999;
}

.record-divider {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1rpx;
  background: repeating-linear-gradient(
    to right,
    #8B8B8B 0,
    #8B8B8B 8rpx,
    transparent 8rpx,
    transparent 16rpx
  );
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 120rpx 0;
  gap: 20rpx;
}

.empty-icon {
  width: 146rpx;
  height: 200rpx;
  margin-top: 250rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}

/* 加载更多样式 */
.load-more {
  padding: 30rpx 0;
  text-align: center;
}

.loading-text {
  color: #999999;
  font-size: 28rpx;
}

.load-more-text {
  color: #CCCCCC;
  font-size: 28rpx;
}
</style>
